<template>
  <view class="my-login">
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <button class="btn" type="warn" open-type="getUserInfo" @getuserinfo="getuserinfo">一键登录</button>
    <!--    <button class="btn" type="warn" open-type="chooseAvatar" @chooseavatar="chooseavatar">获取头像</button>
    <view>{{username}}</view> -->
    <!-- <input type="nickname" v-model="username"> -->

    <view class="text">
      登录后尽享更多权益
    </view>
  </view>
</template>

<script>
  export default {
    name: "my-login",
    data() {
      return {
        username: ''
      };
    },
    // 在登录时获取微信头像与昵称
    // uni.login===>code(身份标识)====>传给后端，后端收到code可实现登录了返回token
    methods: {
      chooseavatar(e) {
        console.log(e);
      },
      async getuserinfo(e) {
        console.log('getuserinfo', e);
        // 用户信息获取
        this.$store.commit('user/setUserInfo', e.detail.userInfo)
        // 登录
        // 先获取code  wx.login
        const res = await uni.login()
        // 调用登录接口
        const res2 = await uni.http.post('/users/wxlogin', {
          encryptedData: e.detail.encryptedData,
          rawData: e.detail.rawData,
          iv: e.detail.iv,
          signature: e.detail.signature,
          code: res.code
        })
        this.$store.commit('user/setToken', res2.message.token)
        // this.$store.commit('user/setToken', 'abc')
        console.log('login', res2);
        // 登录完成
        if (this.$store.state.user.backUrl) {
          uni.reLaunch({
            url: this.$store.state.user.backUrl
          })
          this.$store.commit('user/setBackUrl', '')
        }
      }
    }

  }
</script>

<style lang="scss" scoped>
  .my-login {
    padding: 160rpx 20rpx;
    text-align: center;

    .btn {
      background-color: #c00000;
      border-radius: 40rpx;
      margin-top: 40rpx;
    }

    .text {
      margin-top: 40rpx;
      color: #afafaf;
      font-size: 12px;
    }
  }
</style>